let express = require('express');
let bodyParser = require("body-parser");
let tokenManager = require("../classes/token.js");
let cryptor = require("../classes/crypto.js");

let api = express.Router();

var jsonParser = bodyParser.json();
//rsa加密工具
let cryptoManager = cryptor();

//用户操作实例
let user = require("../classes/user.js");

//处理过程工具
const proc = require("../classes/process.js");

//获取笔记本目录
api.post("/getdir", jsonParser , function( req , res , next ){
    
    //取出token
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.getTopdirOfUser(user_id , req.body).then( userTopDir =>{
           
            // const buf = Buffer.from(userTopDir[0].dirData);
            // const json = JSON.parse(buf);
            // console.log("获取用户目录： ", json );
            
            // 返回该顶级目录
            res.statusCode = 200;
            res.send( JSON.stringify({
                code: 0,
                data:  {
                    data: userTopDir[0],
                    total: userTopDir[1][0].total 
                }
            }) ); // userTopDir.length == 0 ? [] : JSON.parse( Buffer.from(userTopDir[0].dirData) )
            res.end();
        }).catch(userTopDirErr => {
            
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });

    }, next);

    
});

//添加新笔记本
api.post("/changeTopDir", jsonParser , function( req , res , next ){

    console.log("请求参数： ", req.body);
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.updataTopDirOfUser(
            {
                userId: user_id,
                topDirContent: Buffer.from( JSON.stringify(req.body.TopDirContent) , 'utf8' )
            }
        ).then( userTopDir =>{
            
            // 更新顶级目录
            res.statusCode = 200;
            res.send( JSON.stringify({
                code: 0,
                data: userTopDir
            }) );
            res.end();
        }).catch(userTopDirErr => {
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });

    }, next);
    
});

//添加子目录
api.post("/addInnerDir",jsonParser,function( req , res , next ){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.addInnerDirOfUser(
            req.body
        ).then( newInnerDir =>{
            if( newInnerDir.affectedRows > 0 ){
                 // 更新顶级目录
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    data: {
                        inner_id: newInnerDir.insertId,
                        title:  req.body.content.title,
                        common:  req.body.content.common,
                        type: 0
                    },
                    msg: "子目录创建成功"
                }) );
                res.end();
                return ;
            }

            next({
                status: 500,
                code: "500002",
                msg: "服务器忙，稍后再试"
            });
           
        }).catch( newInnerDirErr => {
            console.log("子目录创建 err:", newInnerDirErr);
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });

    }, next);

});

//获取子目录内容
api.post("/getInnerDir",jsonParser,function( req , res , next ){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.getInnerDirOfCurrentDir(
            req.body
        ).then( innerDirContent =>{
           
            // 更新顶级目录
            res.statusCode = 200;
            res.send( JSON.stringify({
                code: 0,
                data: {
                    innerDirs: innerDirContent[0],
                    total: innerDirContent[1][0].total
                }
            }) );
            res.end();
        }).catch(userTopDirErr => {
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });

    },next);

});

//删除目录
api.post("/rmDir", jsonParser , function( req , res , next ){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.removeDir(
            req.body
        ).then( rmdirRes =>{
            
            // 回复删除目录的结果
            if( rmdirRes.length > 0 || rmdirRes.affectedRows > 0  ){
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    msg: "删除成功"
                }) );
                res.end();
                return ;
            }

            next({
                status: 500,
                code: "500002",
                msg: "服务器忙，稍后再试"
            });
            
        }).catch(userTopDirErr => {
            
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });
    }, next);

});

//创建文章
api.post("/mkFile", jsonParser , function( req , res , next){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.createArticle(
            req.body
        ).then( createRes =>{
            
            // 回复删除目录的结果
            if( createRes.affectedRows > 0 ){
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    data:{
                        art_id: createRes.insertId,
                        title: req.body.title,
                        type: 1
                    },
                    msg: "文章创建成功"
                }) );
                res.end();
                return ;
            }

            next({
                status: 500,
                code: "500002",
                msg: "服务器忙，稍后再试"
            });
            
        }).catch(userTopDirErr => {
            
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });
    }, next);

});

//重命名目录
api.post("/rename" , jsonParser , function( req , res , next ){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.reNameOfDirOrArt(
            req.body
        ).then( createRes =>{
           
            //重命名目录的结果
            if( createRes.affectedRows > 0 ){
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    msg: "重命名成功"
                }) );
                res.end();
                return ;
            }

            next({
                status: 500,
                code: "500002",
                msg: "服务器忙，稍后再试"
            });
            
        }).catch(userTopDirErr => {
            console.log("***: ",userTopDirErr);
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });
    },next);

});

//文章编辑
api.post("/saveArticle" , jsonParser , function( req , res , next ){
    
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.changeArtContent(
            req.body
        ).then( saveRes =>{
            // console.log("文章保存结果：", saveRes );
            //重命名目录的结果
            if( saveRes.affectedRows > 0 ){
                res.statusCode = 200;
                res.send( JSON.stringify({
                    code: 0,
                    msg: "保存成功"
                }) );
                res.end();
                return ;
            }

            next({
                status: 500,
                code: "500002",
                msg: "服务器忙，稍后再试"
            });
            
        }).catch(userTopDirErr => {
            console.log("***: ",userTopDirErr);
            next({
                status: 500,
                code: 500001,
                msg: "服务器忙"
                });
            return ;
        });
    },next);

   
});

//获取文章内容
api.post("/getArt" , jsonParser , function( req , res , next ){
    console.log("/getArt reqbody: ", req.body );
    let token = req.headers.token;

    proc.auth_check( token , function( user_id ){
        user.getArticleContent(
                req.body
            ).then( contentRes =>{
                console.log("文章保存结果：", contentRes );
                //获取文章内容结果
                if( contentRes.length > 0 ){
                    res.statusCode = 200;
                    res.send( JSON.stringify({
                        code: 0,
                        data:{
                            content: contentRes[0].art_content
                        }
                    }) );
                    res.end();
                    return ;
                }

                next({
                    status: 500,
                    code: "500002",
                    msg: "服务器忙，稍后再试"
                });
                
            }).catch(userTopDirErr => {
                console.log("***: ",userTopDirErr);
                next({
                    status: 500,
                    code: 500001,
                    msg: "服务器忙"
                    });
                return ;
            });

    }, next);

    
});

//错误处理
api.use(function( err , req , res , next){
    
    if( err ){

        res.statusCode= err.status;
        res.send( JSON.stringify({
            code: err.code,
            msg: err.msg
        }) );
        res.end();
       
    }else{
        next();
    }
    
});


module.exports = api;